﻿namespace VividKit.ServiceModel
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;

    internal static class TraceSourceExtensions
    {
        /// <summary>
        /// Holds a reference for a single serializer of specified type.
        /// </summary>
        /// <typeparam name="T">The type of the T.</typeparam>
        private static class JsonHelper<T>
        {
            private static readonly DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            internal static string Serialize(T obj)
            {
                using (var memoryStream = new MemoryStream())
                {
                    JsonHelper<T>.serializer.WriteObject(memoryStream, obj);
                    return Encoding.Default.GetString(memoryStream.ToArray());
                }
            }
        }

        internal static void TraceObject<T>(this TraceSource log, TraceEventType eventType, int id, T obj)
        {
            if (log.Switch.ShouldTrace(eventType))
            {
                var json = JsonHelper<T>.Serialize(obj);

                if (String.IsNullOrWhiteSpace(json) == false)
                {
                    log.TraceData(eventType, id, obj.GetType().Name + " " + json);
                }
            }
        }
    }
}